<template>
  <div class="textarea resize-y h-24 overflow-scroll relative">
    <div ref="editorRef" />
  </div>
</template>
<script setup>
import { useTemplateRef, onMounted, onBeforeUnmount, watch, ref } from "vue";
import OverType from "overtype";
import { createHighlighter } from "shiki";

const highlighter = await createHighlighter({
  langs: [
    "markdown",
    "json",
    "typescript",
    "javascript",
    "css",
    "html",
    "java",
    "c",
    "cpp",
    "python",
    "bash",
    "xml",
    "vue",
    "vue-html",
    "yaml",
  ],
  themes: ["github-light"],
});

OverType.setCodeHighlighter((code, lang) => {
  return highlighter.codeToHtml(code, { lang, theme: "github-light" });
});

const isPreview = ref(false);

const modelValue = defineModel();
const props = defineProps({
  toolbar: {
    type: Boolean,
    default: false,
  },
});

const editorRef = useTemplateRef("editorRef");

onMounted(() => {
  const [editor] = new OverType(editorRef.value, {
    toolbar: props.toolbar,
    autoResize: true,
    maxHeight: null,
    value: modelValue.value,
    onChange: (value) => {
      if (value && value !== modelValue.value) modelValue.value = value;
    },
  });
  onBeforeUnmount(() => {
    editor.destroy();
    highlighter.dispose();
  });
  watch(modelValue, (newValue) => {
    if (newValue) editor.setValue(newValue);
  });
  watch(isPreview, (val) => {
    if (val) editor.showPreviewMode();
    else editor.showNormalEditMode();
  });
});
</script>
